#!/bin/bash
# Copyright (C) 2015 Yaowen HE
# 
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

default_prefix="/usr/local"
log_file="install.log"

# display help information
# usage: display_help
display_help () {
    echo "usage: install.sh [--prefix=PREFIX] [--tag=TAG] [--help]"
    echo
    echo "  --prefix=PREFIX   install fmark files in PREFIX"
    echo "  --tag=TAG         checkout TAG before installation"
    echo "  --help            display help and exit"
}

# check whether current directory is a git repository
# usage: is_git_repo
is_git_repo () {
    git status > /dev/null 2> /dev/null && return 0 || return 1
}

source src/functions.sh

if has_opt "help" "$@"; then
    display_help
    exit
fi

prefix=$(eval echo $(get_opt "prefix" "$@" || echo $default_prefix))

tag=$(get_opt "tag" "$@")

if [ "$tag" = "" ]; then
    if is_git_repo; then
        tag=$(git show | head -n1 | awk '{ print $2 }')
    else
        tag="UNKNOWN"
    fi
else
    if is_git_repo; then
        if ! git checkout $tag 1> /dev/null 2> /dev/null; then
            echo "error on checking out '$tag'" >&2
            exit 1
        fi
    else
        echo "`pwd` is not a git repository" >&2
        exit 1
    fi
fi

log_msg $log_file "Start installation to \"$prefix\""

dir=("$prefix"\
    "$prefix"/bin\
    "$prefix"/etc\
    "$prefix"/share\
    "$prefix"/share/fmark)

for d in ${dir[@]}; do
    [ -d "$d" ] || log_msg $log_file "$(mkdir -vp "$d")"
done

sed "s#@tag@#$tag#g;s#@prefix@#$prefix#g" src/fmark.sh > "$prefix"/bin/fmark
log_msg $log_file "src/fmark.sh->"$prefix"/bin/fmark"
log_msg $log_file "$(chmod +x -v "$prefix"/bin/fmark)"

log_msg $log_file "$(install -v -m0644 src/functions.sh "$prefix"/share/fmark/functions.sh)"

for f in $(ls src/fmark-*.sh 2> /dev/null); do
    log_msg $log_file "$(install -v -m0644 $f "$prefix"/share/fmark/$(basename $f))"
done

log_msg $log_file "$(install -v -b -m0644 src/fmark.conf "$prefix"/etc/fmark.conf)"

log_msg $log_file "Finish installation"
